/**
 *
 * @(#)Common.java    Jul 19, 2010
 *
 * Copyright 2010 QinYu, Inc. All rights reserved.
 *
 */
package com.ligux.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import com.ligux.flzyup.R;


/**
 *
 * @author Johnny Lu
 *
 */
public class Common {
	
	private static final ProcessBuilder pb = new ProcessBuilder(findBinaryPath(Constant.CMD_SU));

	public static void showMessage(Context context, final String cmd, String title, String msg) {
		AlertDialog dialog;
		final String liguxBinary = context.getFilesDir().getPath() + "/" + Constant.CMD_TOOLBOX;
		dialog = new AlertDialog.Builder(context)
		.setIcon(android.R.drawable.ic_dialog_alert)
		.setTitle(title)
		.setMessage(msg)
		.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					Log.i(Constant.TAG, "Reboot starting...");
					Process process = pb.start();
					PrintStream stdin = new PrintStream(process.getOutputStream());
					stdin.println(liguxBinary + " " + cmd);
					stdin.flush();
					stdin.close();
					Log.i(Constant.TAG, "Reboot finished");
				} catch (IOException e) {
					Log.e(Constant.TAG, "reboot failed");
					e.printStackTrace();
				}
			}
		})
		.setNegativeButton(R.string.no, null)
		.create();
		dialog.show();
	}
	
	public static void initialization(Context context) {
		// /data/data/com.ligux.main/files
		File file = context.getFilesDir();
		try {
			InputStream is = context.getAssets().open(Constant.CMD_TOOLBOX);
			OutputStream os = new FileOutputStream(new File(file, Constant.CMD_TOOLBOX));//new File(URI.create(file.toString() + "/toolbox"))
			byte[] buf = new byte[1024];
			int len;
			while ((len = is.read(buf)) > 0) {
				os.write(buf, 0, len);
			}
			os.close();
			is.close();
			Process process = Runtime.getRuntime().exec("chmod 777 " + context.getFilesDir().getPath()  + "/" + Constant.CMD_TOOLBOX);
			process.waitFor();
			Log.i(Constant.TAG, "Initialize LiGux Tools completely!");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static String findBinaryPath(String executable) {
		for (String binPath : new String[]{Constant.BIN_PATH, Constant.XBIN_PATH}) {
			String path = binPath + "/" + executable;
			if ( new File(path).exists() )
				return path;
		}
		return executable;
	}
}
